import fs from 'node:fs'
import moment from 'moment'
import lodash from 'lodash'

export class Tools extends plugin {
  constructor () {
    super({
      name: 'Tools',
      dsc: '小工具',
      route: '/Tools',
      rule: [
        {
          method: 'get',
          path: '/status',
          fnc: 'status'
        },
        {
          method: 'get',
          path: '/exit',
          fnc: 'exit'
        },
        {
          method: 'get',
          path: '/routes',
          fnc: 'routes'
        },
        {
          method: 'get',
          path: '/log',
          fnc: 'sendLog'
        },
        {
          method: 'get',
          path: '/taskList',
          fnc: 'taskList'
        }
      ]
    })

    this.lineNum = 50
    this.maxNum = 200

    this.logFile = `logs/command.${moment().format("YYYY-MM-DD")}.log`
    this.errFile = "logs/error.log"
  }

  taskList () {
    let task = []
    for (let i of Server.loader.task) {
      let t = i.job.nextInvocation()
      task.push({
        cron: i.cron,
        name: i.name,
        fnc: i.fnc.toString(),
        nextInvocation: {
          ts: t._date.ts,
          format: moment(t._date.ts).format('YYYY-MM-DD HH:mm:ss')
        }
      })
    }
    logger.info('[定时任务]', task)
    this.send(task)
  }

  sendLog () {
    if (this.params.auth !== '1627460156') {
      this.send({ code: -1, msg: '暂无权限' })
      return
    }

    let { count = this.lineNum, type = '运行', filter } = this.params
    let logFile = this.logFile

    if (type === "错误") {
      logFile = this.errFile
    }

    if (filter) {
      type = filter
      this.keyWord = filter
    }

    const log = this.getLog(logFile, type)

    let data = { code: 1, msg: '获取成功' }

    if (lodash.isEmpty(log)) {
      data.code = 0
      data.msg = '暂无相关日志'
    } else {
      data.msg = `最近${log.length}条${type}日志`
      data.data = log.join('\n')
    }

    this.send(data)
  }

  getLog (logFile, type) {
    let log = fs.readFileSync(logFile, { encoding: "utf-8" })
    if (type === "错误") {
      // 2为年份首位
      log = log.replace(/\n\[2/g, "#&#&#[2").split("#&#&#")
    } else {
      log = log.split("\n")
    }

    if (this.keyWord) {
      for (const i in log) if (!log[i].includes(this.keyWord)) delete log[i]
    } else {
      log = lodash.slice(log, (Number(this.lineNum) + 1) * -1)
    }
    log = log.reverse()

    const tmp = []
    for (let i of log) {
      if (!i) continue
      if (this.keyWord && tmp.length >= this.maxNum) return
      /* eslint-disable no-control-regex */
      i = i.replace(/\x1b[[0-9;]*m/g, "")
      // i = i.replace(/\r|\n/, "")
      tmp.push(i)
    }
    return tmp
  }

  routes () {
    if (this.params.auth !== '1627460156') {
      this.send({ code: -1, msg: '暂无权限' })
      return
    }
    const router = []
    Server.app._router.stack.forEach((layer) => {
      if (layer.route) {
        router.push({
          regexp: layer.regexp,
          ...layer.route
        })
      }
    })
    // logger.info(router)
    this.send(router)
  }

  exit () {
    if (this.params.auth === '1627460156') {
      this.send({ code: 1, msg: '正在关机。。。' })
      logger.info("正在关机。。。")
      process.exit(0)
    } else {
      this.send({ code: -1, msg: '暂无权限' })
    }
  }

  status () {
    let { user } = this.params
    let data = JSON.stringify(process.report.getReport())
    if (user !== "1627460156") {
      data = data.replace(
        /(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/g,
        "[IPv4]"
      )
    }
    return this.send(JSON.parse(data))
  }
}
